package org.xp.judgeplatform.controller;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.xp.judgeplatform.common.ApiResponse;
import org.xp.judgeplatform.pojo.vo.JudgeVO.JudgeResultVO;

import org.springframework.web.bind.annotation.*;
import org.xp.judgeplatform.exception.BusinessException;
import org.xp.judgeplatform.pojo.dto.JudgeDTO.JudgeRequestDTO;
import org.xp.judgeplatform.security.UserPrincipal;
import org.xp.judgeplatform.service.JudgeService;

import jakarta.validation.Valid;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/judge")
@CrossOrigin(origins = {"http://localhost:5173", "http://localhost:3000"}, allowCredentials = "false")
@Validated
public class JudgeController {
    
    private final JudgeService judgeService;
    
    /**
     * 提交代码进行判题
     * 
     * @param request 判题请求
     * @return 判题结果
     */
    @PostMapping("/submit")
    public ApiResponse<JudgeResultVO> submitCode(
            @RequestBody @Valid JudgeRequestDTO request,
            Authentication  authentication) {

        UserPrincipal principal = (UserPrincipal) authentication.getPrincipal();
        if (!principal.getId().equals(request.getUserId())) {
            return ApiResponse.error("无权以其他用户身份提交代码");
        }

        log.info("收到代码提交请求 - 题目ID: {}, 用户ID: {}, 语言: {}", 
                request.getProblemId(), request.getUserId(), request.getLanguage());
        
        // 参数验证（@Valid注解已经处理了基本验证）
        if (request.getCode() == null || request.getCode().trim().isEmpty()) {
            throw new BusinessException(400, "代码不能为空");
        }
        
        if (request.getFunctionName() == null || request.getFunctionName().trim().isEmpty()) {
            request.setFunctionName("solution"); // 设置默认函数名
        }

        JudgeResultVO result = judgeService.judgeCode(request);
        
        log.info("判题完成 - 状态: {}, 分数: {}/{}, 通过用例: {}/{}", 
                result.getStatus().getCode(), result.getScore(), result.getTotalScore(),
                result.getPassedCases(), result.getTotalCases());
        
        return ApiResponse.success(result);
    }
    
    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ApiResponse<String> health() {
        return ApiResponse.success("Judge service is running");
    }
}
